import { useMatches } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { ItemType } from 'antd/es/breadcrumb/Breadcrumb';
import { Breadcrumb } from 'antd';
import { useFlattenedRoutes } from '@/router/hooks';

const IBreadCrumb = () => {
  const matches = useMatches();
  const flattenedRoutes = useFlattenedRoutes();
  const [breadCrumbs, setBreadCrumbs] = useState<ItemType[]>([]);

  useEffect(() => {
    const paths = matches.filter((item) => item.pathname !== '/').map((item) => item.pathname);
    const pathRouteMetas = flattenedRoutes.filter((item) => paths.indexOf(item.key) !== -1);

    const result: ItemType[] = [];

    pathRouteMetas.forEach((i, idx) => {
      if (i.hideBreadcrumb) return;
      if (idx == pathRouteMetas.length - 1) {
        result.push({
          title: i.label,
        });
      } else {
        result.push(
          {
            title: i.label,
            href: i.disabled ? undefined : i.key,
          },
          {
            type: 'separator', // Must have
            separator: (
              <div
                style={
                  idx === pathRouteMetas.length - 2 ? { color: 'var(--ycx-font-color-l1)' } : {}
                }
              >
                /
              </div>
            ),
          },
        );
      }
    });

    setBreadCrumbs(result);
  }, [flattenedRoutes, matches]);

  if (breadCrumbs.length === 0) {
    return null;
  }

  return (
    <div
      style={{
        padding: '24px 40px 16px',
        boxShadow: '0 0.5px 0 0 var(--ycx-divider-color)',
      }}
    >
      <Breadcrumb items={breadCrumbs} className="cursor-default text-base" separator="" />
    </div>
  );
};

export default IBreadCrumb;
